//
//  YZMNewReviewHomeViewController.m
//  YZMicroStock
//
//  Created by apple on 2017/12/13.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMNewReviewHomeViewController.h"
#import "YZMHomePageSectionView2.h"
#import "YZMHomePageCell.h"
#import "YZMInfoViewController.h"
#import "SDCycleScrollView.h"
#import "YZDKnowledgeViewController.h"
#import "YZMyStocksTopCell.h"
#import "YZGeneralResultModel.h"
#import "YZClient+Quote.h"
#import "OtherPageView.h"
#import "YZMBundleVersionControlService.h"




static NSString *const identifier = @"YZMHomePageCell";

@interface YZMNewReviewHomeViewController ()<UITableViewDelegate,UITableViewDataSource,YZMHomePageSectionView2Delegate>

@property (nonatomic, strong) NSMutableArray *arrData;

@property (weak, nonatomic) IBOutlet UITableView *tableViewContainer;

@property (nonatomic, strong) YZMHomePageSectionView2 *viewSection;

@property (strong, nonatomic) IBOutlet UIView *viewHeader;

@property (weak, nonatomic) IBOutlet SDCycleScrollView *cycleScrollView;

@property (weak, nonatomic) IBOutlet UIView *viewStock;

@property (strong, nonatomic)  YZMyStocksTopCell *stockTopCell;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) OtherPageView *otherPageView;

@end

@implementation YZMNewReviewHomeViewController{
    NSMutableDictionary *_realDataDict;
    BOOL _unShowErrorFlag;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _realDataDict = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self startTimer];
    [self fetchStockDetailInfo];
    [self fetchData];
    [self configView];
}

- (void)startTimer{
    if (self.timer == nil) {
        self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fetchStockDetailInfo) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}


- (void)configView{
    self.title = @"首页";
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
     self.navigationItem.title = infoDic[@"CFBundleDisplayName"];
    self.view.backgroundColor = [YZMAppStyle colorForMain];
    self.cycleScrollView.autoScrollTimeInterval = 3.0;
    self.cycleScrollView.localizationImageNamesGroup = @[[UIImage imageNamed:@"banner4.png"]];
    self.stockTopCell.contentView.backgroundColor = [YZMAppStyle colorForMain];
    self.stockTopCell = [[YZMyStocksTopCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"stockTop"];
    self.stockTopCell.contentView.backgroundColor = [YZMAppStyle  colorForMain];
    [self.viewStock addSubview:self.stockTopCell.contentView];
    [self.stockTopCell.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.viewStock);
    }];
    _tableViewContainer.tableHeaderView = self.viewHeader;
    _tableViewContainer.backgroundColor = [YZMAppStyle colorForMain];
    [_tableViewContainer registerNib:[UINib nibWithNibName:NSStringFromClass([YZMHomePageCell class]) bundle:nil] forCellReuseIdentifier:identifier];
    _tableViewContainer.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)fetchData{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"trade" ofType:@"json"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    _arrData = [NSMutableArray array];
    for (NSInteger i = 0; i < 4; i++) {
        [_arrData addObject:arr[i]];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arrData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZMHomePageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    NSDictionary *dic  = self.arrData[indexPath.row];
    [cell configCellWithDic:dic];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.viewSection;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = self.arrData[indexPath.row];
    [YZMHCMInstance pushViewControllerWithName:NSStringFromClass([YZDKnowledgeViewController class]) andParams:dic];
}

#pragma mark - network
- (void)fetchStockDetailInfo{
    
//    if ([self checkNetwork]) {
//        _unFirstFetchAStockFlag=YES;
//        return;
//    }
    NSMutableArray *array = [NSMutableArray array];
    
    [array addObject:@"SH000001"];
    [array addObject:@"SZ399001"];
    [array addObject:@"SZ399006"];
    if (!_otherPageView) {
        [self showLoading];
    }
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        [self hiddenLoading];
        YZGeneralResultModel *topModel = responseObject;
        if(topModel.success){
            [_realDataDict removeAllObjects];
            [_realDataDict addEntriesFromDictionary:topModel.data];
            self.stockTopCell.leftRecord = _realDataDict[@"SH000001"];
            self.stockTopCell.middleRecord = _realDataDict[@"SZ399001"];
            self.stockTopCell.rightRecord = _realDataDict[@"SZ399006"];
            _unShowErrorFlag = NO;
        }else{
            if (!_unShowErrorFlag) {
                [topModel showMessage];
            }
            _unShowErrorFlag=YES;
        }
    } failure:^(NSError *error) {
        [self showErrorWithTryBlock:^{
            [[YZMBundleVersionControlService sharedService] setIsRun:NO];
            [[YZMBundleVersionControlService sharedService] fecthBundVersion];
            do {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            } while (![[YZMBundleVersionControlService sharedService] isRun]);
                [self fetchStockDetailInfo];
                [YZMControllerManager initAndEnter];
        }];
        if (!_unShowErrorFlag) {
            
            if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
                
                [error yz_showMessage];
            }
        }
        _unShowErrorFlag = YES;
    }];
}

#pragma mark - YZMHomePageSectionView2Delegate

- (void)pushVc{
    YZMInfoViewController *vc = [[YZMInfoViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [YZMHCMInstance pushViewController:vc animated:YES];
    //    [YZMHCMInstance pushViewControllerWithName:NSStringFromClass([YZMInfoViewController class]) andParams:nil];
}

#pragma mark - getter

- (YZMHomePageSectionView2 *)viewSection{
    if (!_viewSection) {
        _viewSection = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMHomePageSectionView2 class]) owner:self options:nil][0];
        _viewSection.backgroundColor = [YZMAppStyle colorForMain];
        _viewSection.deletegate = self;
    }
    return _viewSection;
}

- (void)showLoading{
    _otherPageView.hidden = NO;
    if (_otherPageView) {
        
        return;
    }
    UIWindow *wd = [[UIApplication sharedApplication].delegate window];
    self.otherPageView.btnTry.hidden = YES;
    [wd addSubview:self.otherPageView];
    [self.otherPageView.activityIndicator startAnimating];
    [self.otherPageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(wd);
    }];
}

- (void)showErrorWithTryBlock:(void(^)())tryBlock{
    self.otherPageView.hidden = NO;
    self.otherPageView.tryBlock = tryBlock;
     [self.otherPageView.activityIndicator stopAnimating];
    self.otherPageView.activityIndicator.hidden = YES;
    self.otherPageView.btnTry.hidden = NO;
    self.otherPageView.lableInfo.text = @"网络无法连接，请联网后重试";
}

- (void)hiddenLoading{
    self.otherPageView.hidden = YES;
}

- (OtherPageView *)otherPageView{
    if (!_otherPageView) {
        _otherPageView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([OtherPageView class]) owner:self options:nil][0];
        _otherPageView.backgroundColor = [YZMAppStyle colorForMain];
    }
    return _otherPageView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
